﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OpenCvSharp;
using System.Diagnostics;

namespace LicenseAutoDetection
{
    class ImageLoad : IDisposable
    {
        IplImage src, dst;

        public void Loading(String filename, int option, out IplImage _src)
        {
            const int IMAGE_BOUND = 2000;
            const int IMAGE_SIZE = 500;
            int reduceSize = 1;

            try
            {
                src = (option == 3) ? new IplImage(filename, LoadMode.AnyColor) :
                                      new IplImage(filename, LoadMode.GrayScale);

                if (src.Width <= IMAGE_SIZE || src.Height <= IMAGE_SIZE)
                {
                    _src = null;
                }
                else
                {
                    if (src.Width >= IMAGE_BOUND && src.Height >= IMAGE_BOUND)
                    {
                        reduceSize = (int)((src.Width + src.Height) / IMAGE_BOUND);
                        dst = new IplImage(Cv.Size(src.Width / reduceSize, src.Height / reduceSize), BitDepth.U8, option);

                        Cv.Resize(src, dst, Interpolation.Area);

                        _src = dst;
                    }
                    else
                    {
                        _src = src;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(filename + ": " + ex.Message);
                _src = null;
            }
        }

        #region IDisposable 구현
        private bool disposed = false;

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    if (src != null) { src.Dispose(); src = null; }
                    if (dst != null) { dst.Dispose(); dst = null; }
                }

                disposed = true;
            }
        }

        ~ImageLoad()
        {
            Dispose(false);
        }
        #endregion
    }
}